#include "addbasketballtodbwidget.h"
#include <QDebug>
#include <QSqlQuery>
#include <QGroupBox>
#include <QLabel>

#define CurDate()  m_DateEdit->date().toString("yyyy-MM-dd")

AddBasketBallToDBWidget::AddBasketBallToDBWidget(QWidget *parent) :
    QWidget(parent)
{
    setAutoFillBackground(true);

    QGroupBox * BoolHGroup = new QGroupBox(tr("basketboll_history"));
    m_SubmitBtn = new QPushButton("Submit",BoolHGroup);
    m_SyncBtn = new QPushButton("Sync",BoolHGroup);
    m_DateEdit = new QDateEdit(BoolHGroup);
    m_TextEdit = new QTextEdit(BoolHGroup);

    m_DateEdit->setDisplayFormat("yyyy-MM-dd");
    m_DateEdit->setDate(QDate::currentDate());

    QGroupBox * G2BallGroup = new QGroupBox(tr("basketboll"));
    QLabel *ComparefractionLabel = new QLabel("G2Comparefraction:",G2BallGroup);
    m_G2ComparefractionEdit = new QLineEdit(G2BallGroup);
    ComparefractionLabel->setBuddy(m_G2ComparefractionEdit);

    m_G2HTCombox =  new QComboBox(G2BallGroup);
    QLabel *G2HTComboxLabel = new QLabel("G2HomeTeam:",G2BallGroup);
    G2HTComboxLabel->setBuddy(m_G2HTCombox);

    m_G2MultipleEdit = new QLineEdit(G2BallGroup);
    QLabel *G2MultipleLabel = new QLabel("G2Multiple:",G2BallGroup);
    G2MultipleLabel->setBuddy(m_G2MultipleEdit);

    m_G2ResultEdit =  new QLineEdit(G2BallGroup);
    QLabel *G2ResultLabel = new QLabel("G2Result:",G2BallGroup);
    G2ResultLabel->setBuddy(m_G2ResultEdit);

    m_G2VTCombox =  new QComboBox(G2BallGroup);
    QLabel *G2VTComboxLabel = new QLabel("G2VisitingTeam:",G2BallGroup);
    G2VTComboxLabel->setBuddy(m_G2VTCombox);

    m_G2SubmitBtn = new QPushButton("G2Submit");

    m_G2DateEdit = new QDateEdit(G2BallGroup);
    QLabel *G2DateLabel = new QLabel("G2Date:",G2BallGroup);
    G2DateLabel->setBuddy(m_G2DateEdit);


    m_G2DateEdit->setDisplayFormat("yyyy-MM-dd");
    m_G2DateEdit->setDate(QDate::currentDate().addDays(1));

    QString q_cmd = "SELECT DISTINCT HomeTeam FROM t_basketboll_history";
    QSqlQuery query;
    query.exec(q_cmd);
    QStringList ComboxList;
    while (query.next())
    {
        ComboxList << query.value("HomeTeam").toString();
    }

    q_cmd = "SELECT DISTINCT VisitingTeam FROM t_basketboll_history";
    query.exec(q_cmd);
    while (query.next())
    {
        if(ComboxList.indexOf(query.value("VisitingTeam").toString()) == -1)
            ComboxList << query.value("VisitingTeam").toString();
    }

    m_G2VTCombox->addItems(ComboxList);
    m_G2HTCombox->addItems(ComboxList);

    QHBoxLayout *hLayoutG2 = new QHBoxLayout();
    QVBoxLayout *vLayoutG2 = new QVBoxLayout();
    hLayoutG2->addWidget(G2DateLabel);
    hLayoutG2->addWidget(m_G2DateEdit);
    hLayoutG2->addWidget(G2VTComboxLabel);
    hLayoutG2->addWidget(m_G2VTCombox);
    hLayoutG2->addWidget(G2HTComboxLabel);
    hLayoutG2->addWidget(m_G2HTCombox);
    hLayoutG2->addWidget(G2MultipleLabel);
    hLayoutG2->addWidget(m_G2MultipleEdit);
    hLayoutG2->addWidget(ComparefractionLabel);
    hLayoutG2->addWidget(m_G2ComparefractionEdit);
    hLayoutG2->addWidget(G2ResultLabel);
    hLayoutG2->addWidget(m_G2ResultEdit);
    hLayoutG2->addWidget(m_G2SubmitBtn);

    vLayoutG2->addWidget(G2BallGroup);
    vLayoutG2->addLayout(hLayoutG2);

    connect(m_G2SubmitBtn,SIGNAL(clicked()),this,SLOT(OnG2SubmitBtnClicked()));

    connect(m_SubmitBtn,SIGNAL(clicked()),this,SLOT(OnSubmitBtnClicked()));

    connect(m_SyncBtn,SIGNAL(clicked()),this,SLOT(OnSyncBtnClicked()));

    QHBoxLayout *hLayout = new QHBoxLayout();

    hLayout->addWidget(m_DateEdit,0,Qt::AlignLeft);
    hLayout->addWidget(m_SubmitBtn);
    hLayout->addWidget(m_SyncBtn,1,Qt::AlignRight);
    hLayout->addStretch();
    QVBoxLayout *vLayout = new QVBoxLayout();
    vLayout->addWidget(BoolHGroup);
    vLayout->addWidget(m_TextEdit);
 //   vLayout->addStretch();
    vLayout->addLayout(hLayout);
  //  vLayout->addStretch();


    vLayout->addLayout(vLayoutG2);
    vLayout->addStretch();



    setLayout(vLayout);

  //  GetRecoed_HV3_HVO5("v","hometeam");

}

void AddBasketBallToDBWidget::OnSyncBtnClicked()
{
    qDebug()<< "OnSubmitBtnClicked";
    QString str = m_TextEdit->toPlainText();


    str = str.remove(" ");
    qDebug()<< str;

    QStringList firstList = str.split("\n");

    if(firstList.isEmpty())
        return ;


        QStringList list = str.split("\n");
        qDebug() << "list:" << list;

        qDebug() << list.indexOf(QRegExp("(.*)-(.*)"),0);

        int find_index = 0;
        do
        {
            find_index = list.indexOf(QRegExp("(.*)-(.*)"),find_index+1);

            QStringList HVList;
            if(find_index > 0)
                HVList =  list.at(find_index).split("-");
            if(find_index > 0 && list.count() >= (find_index+1)  && HVList.count() == 2 && HVList.at(0).toInt() > 0 &&  HVList.at(1).toInt() > 0 )
            {
                qDebug() << list.at(find_index-1)  << list.at(find_index)  << list.at(find_index+1);
                if(!G2ItemExists2Updates( list.at(find_index-1) ,list.at(find_index+1) , list.at(find_index) ,CurDate()))
                {
         /*           QString q_cmd = QString ("INSERT INTO t_basketboll_history (Date ,"
                                             "VisitingTeam  ,HomeTeam  ,"
                                             "Result ,IsNBA) "
                                             "VALUES ('%1','%2','%3','%4','NBA' )" ).arg(CurDate())
                            .arg(list.at(find_index-1))
                            .arg(list.at(find_index+1))
                            .arg(list.at(find_index));

                    QSqlQuery q;
                    q.exec(q_cmd);*/
                }
            }
        }
        while(find_index != -1);

}

void AddBasketBallToDBWidget::OnG2SubmitBtnClicked()
{
    QString G2DateStr = m_G2DateEdit->date().toString("yyyy-MM-dd");
    QString G2VTStr = m_G2VTCombox->currentText();
    QString G2HTStr = m_G2HTCombox->currentText();
    QString G2MultipleStr = m_G2MultipleEdit->text();
    QString G2ComparefractionStr = m_G2ComparefractionEdit->text();
    QString G2ResultStr = m_G2ResultEdit->text();

    if(G2VTStr == G2HTStr)
    {
        return;
    }
    QString q_cmd = QString ("INSERT INTO t_basketboll (Date , CompareType,"
                             "HomeTeam  ,VisitingTeam  ,"
                             "Result ,Comparefraction ,"
                             "Recoed ,Multiple ) "
                             "VALUES ('%1', 'BS' ,'%2','%3','%4','%5' ,'%6' , '%7' )" )
            .arg(G2DateStr)
            .arg(G2HTStr)
            .arg(G2VTStr)
            .arg(G2ResultStr)
            .arg(G2ComparefractionStr)
            .arg(GetRecoed_HV3_HVO5(G2VTStr,G2HTStr))
            .arg(G2MultipleStr);
    QSqlQuery query;
    query.exec(q_cmd);
    qDebug() << "q_cmd :" << q_cmd;

}

void AddBasketBallToDBWidget::OnSubmitBtnClicked()
{
    qDebug()<< "OnSubmitBtnClicked";
    QString str = m_TextEdit->toPlainText();


    str = str.remove(" ");
    qDebug()<< str;

    QStringList firstList = str.split("\n");

    if(firstList.isEmpty())
        return ;


        QStringList list = str.split("\n");
        qDebug() << "list:" << list;

        qDebug() << list.indexOf(QRegExp("(.*)-(.*)"),0);

        int find_index = 0;
        do
        {
            find_index = list.indexOf(QRegExp("(.*)-(.*)"),find_index+1);

            QStringList HVList;
            if(find_index > 0)
                HVList =  list.at(find_index).split("-");
            if(find_index > 0 && list.count() >= (find_index+1)  && HVList.count() == 2 && HVList.at(0).toInt() > 0 &&  HVList.at(1).toInt() > 0 )
            {
                qDebug() << list.at(find_index-1)  << list.at(find_index)  << list.at(find_index+1);
                if(!ItemExists( list.at(find_index-1) ,list.at(find_index+1) , list.at(find_index) ,CurDate()))
                {
                    QString q_cmd = QString ("INSERT INTO t_basketboll_history (Date ,"
                                             "VisitingTeam  ,HomeTeam  ,"
                                             "Result ,IsNBA) "
                                             "VALUES ('%1','%2','%3','%4','NBA' )" ).arg(CurDate())
                            .arg(list.at(find_index-1))
                            .arg(list.at(find_index+1))
                            .arg(list.at(find_index));

                    QSqlQuery q;
                    q.exec(q_cmd);
                }
            }
        }
        while(find_index != -1);


}


bool AddBasketBallToDBWidget::ItemExists(const QString& VisitingTeam,const QString& HomeTeam, const QString& Result, const QString& Date)
{
    QSqlQuery query;
    QString q_cmd = QString("SELECT * FROM t_basketboll_history WHERE VisitingTeam = '%1' AND HomeTeam = '%2' AND Result = '%3' AND Date = '%4'")
            .arg(VisitingTeam)
            .arg(HomeTeam)
            .arg(Result)
            .arg(Date);
    query.exec(q_cmd);
    qDebug()<< " AddBasketBallToDBWidget::ItemExists" << q_cmd;

    while (query.next())
    {

        qDebug()<< "true";
        return true;

    }

    qDebug()<< "False";

    return false;
}

bool AddBasketBallToDBWidget::G2ItemExists2Updates(const QString& VisitingTeam,const QString& HomeTeam, const QString& Result, const QString& Date)
{

    QStringList ResultList = Result.split("-");
    if(ResultList.count() !=2  || ResultList.at(0).toInt() <=0 || ResultList.at(1).toInt() <=0 )
        return false;


    QSqlQuery query;
    QString q_cmd = QString("SELECT * FROM t_basketboll WHERE VisitingTeam = '%1' AND HomeTeam = '%2' AND Date = '%3'")
            .arg(VisitingTeam)
            .arg(HomeTeam)
            .arg(Date);
    query.exec(q_cmd);
    qDebug()<< " AddBasketBallToDBWidget::ItemExists" << q_cmd;

    while (query.next())
    {

        QString HVResult = QString("HV=%1:%2").arg(ResultList.at(1)).arg(ResultList.at(0));

        QString cmd =QString( "UPDATE t_basketboll SET Result = '%1'  WHERE VisitingTeam = '%2' AND HomeTeam = '%3' AND Date = '%4'")
                .arg(HVResult)
                .arg(VisitingTeam)
                .arg(HomeTeam)
                .arg(Date);
        QSqlQuery q;
        q.exec(cmd);

        qDebug()<< "true";
        return true;

    }

    qDebug()<< "False";

    return false;
}
QString AddBasketBallToDBWidget::GetRecoed_HV3_HVO5(const QString& VisitingTeam,const QString& HomeTeam)
{

    QStringList list;
    int count = 0;
    QString RetStr;
    count = GetRecoed_HV_NOHVSORT(VisitingTeam,HomeTeam,&list,3);
    qDebug() <<"HV:=" << list << count;
    if(list.count() == 3)
        RetStr += QString("HV=%1;%2;%3\n")
                .arg(list.at(0))
                .arg(list.at(1))
                .arg(list.at(2));
    else if(list.count() == 2)
        RetStr += QString("HV=%1;%2\n")
                .arg(list.at(0))
                .arg(list.at(1));
    else if(list.count() == 1)
        RetStr += QString("HV=%1\n")
                .arg(list.at(0));

    count = GetRecoed_HO_NOHOSORT(HomeTeam,&list,5);
    qDebug() << "HO:=" << list;
    if(list.count() == 5)
     RetStr += QString("HO=%1;%2;%3;%4;%5\n")
            .arg(list.at(0))
            .arg(list.at(1))
            .arg(list.at(2))
            .arg(list.at(3))
            .arg(list.at(4));
    count = GetRecoed_VO_NOVOSORT(VisitingTeam,&list,5);
    qDebug() <<"VO:=" << list;
    if(list.count() == 5)
        RetStr += QString("VO=%1;%2;%3;%4;%5")
               .arg(list.at(0))
               .arg(list.at(1))
               .arg(list.at(2))
               .arg(list.at(3))
               .arg(list.at(4));

    qDebug() << RetStr.replace("-",":");
    return RetStr;
}


// return count;
int AddBasketBallToDBWidget::GetRecoed_HV_NOHVSORT(const QString& VisitingTeam,const QString& HomeTeam,QStringList *list ,int count)
{
    if(list == NULL)
        return -1;

    list->clear();

    QSqlQuery query;
    QString q_cmd = QString("SELECT  \"Result\",\"Date\" , \"VisitingTeam\"  FROM t_basketboll_history WHERE (VisitingTeam = '%1' AND HomeTeam = '%2') OR (VisitingTeam = '%3' AND HomeTeam = '%4')  ORDER BY \"Date\" DESC LIMIT  %5")
            .arg(VisitingTeam)
            .arg(HomeTeam)
            .arg(HomeTeam)
            .arg(VisitingTeam)
            .arg(count);
    query.exec(q_cmd);
    while (query.next())
    {
        if(query.value("VisitingTeam").toString() == HomeTeam)
        {
            *list <<  query.value("Result").toString();
        }
        else
        {
            QStringList tmplist = query.value("Result").toString().split("-");
            if(tmplist.count() == 2)
            {
                *list << QString("%1-%2").arg(tmplist.at(1)).arg(tmplist.at(0));
            }
        }
    }
//    qDebug()<< "AddBasketBallToDBWidget::GetRecoed_HO_NOHOSORT::q_cmd" << q_cmd;
    return list->count();
}
int AddBasketBallToDBWidget::GetRecoed_HO_NOHOSORT(const QString& HomeTeam,QStringList *list ,int count)
{
    if(list == NULL)
        return -1;

    list->clear();

    QSqlQuery query;
    QString q_cmd = QString("SELECT  \"Result\",\"Date\" , \"VisitingTeam\" FROM t_basketboll_history WHERE VisitingTeam = '%1' OR HomeTeam = '%2' ORDER BY \"Date\" DESC LIMIT  %3")
            .arg(HomeTeam)
            .arg(HomeTeam)
            .arg(count);
    query.exec(q_cmd);
    while (query.next())
    {
        if(query.value("VisitingTeam").toString() == HomeTeam)
        {
            *list <<  query.value("Result").toString();
        }
        else
        {
            QStringList tmplist = query.value("Result").toString().split("-");
            if(tmplist.count() == 2)
            {
                *list << QString("%1-%2").arg(tmplist.at(1)).arg(tmplist.at(0));
            }
        }
    }
//    qDebug()<< "AddBasketBallToDBWidget::GetRecoed_HO_NOHOSORT::q_cmd" << q_cmd;
    return list->count();

}
int AddBasketBallToDBWidget::GetRecoed_VO_NOVOSORT(const QString& VisitingTeam,QStringList *list ,int count)
{
    if(list == NULL)
        return -1;

    list->clear();

    QSqlQuery query;
    QString q_cmd = QString("SELECT  \"Result\",\"Date\" ,\"VisitingTeam\" FROM t_basketboll_history WHERE VisitingTeam = '%1' OR HomeTeam = '%2' ORDER BY \"Date\" DESC LIMIT  %3")
            .arg(VisitingTeam)
            .arg(VisitingTeam)
            .arg(count);
    query.exec(q_cmd);
    while (query.next())
    {
        if(query.value("VisitingTeam").toString() == VisitingTeam)
        {
            *list <<  query.value("Result").toString();
        }
        else
        {
            QStringList tmplist = query.value("Result").toString().split("-");
            if(tmplist.count() == 2)
            {
                *list << QString("%1-%2").arg(tmplist.at(1)).arg(tmplist.at(0));
            }
        }
    }
//    qDebug()<< "AddBasketBallToDBWidget::GetRecoed_VO_NOVOSORT::q_cmd" << q_cmd;
    return list->count();
}
